Online-Academy
Look, Read, Understand, Apply

underscore _

In Python, the underscore character _ is a special symbol that is used in several different ways depending on the context. It doesn't have just one meaning — Python programmers use it for multiple purposes. Here are the most common uses:

Temporary or "throwaway" variable
  • _ is often used when you don't care about the variable value.
  • It tells other programmers: "This value is not important."
for _ in range(5):
    print("Hello")
Explanation:
  • The loop runs 5 times, but the variable isn't needed.
  • _ is used instead of a real variable name.
a, _, x = (110, 120, 30)
print(a, x)
output: 110 30
Here 120 is ignored.

In the Python interactive shell, _ stores the last result. Example:

>>> 5 + 3
8
>>> _ * 2
16

Separating digits in numbers: Python allows _ to make large numbers easier to read. Example:

num = 1_000_000
print(num)

Private variables (by convention): A single underscore before a variable means "internal use". Example:

class Employee:
    def __init__(self):
        self._name = "Sheetal"

Special methods (double underscore): Double underscores __ are used for special Python methods. Example:

class A:
    def __init__(self):
        print("Object created")